<template>
  <view class="container">
    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-info">
        <view class="avatar-section">
          <image
            v-if="userInfo.avatar"
            :src="userInfo.avatar"
            class="avatar"
            @click="selectAvatar"
          />
          <view v-else class="avatar-placeholder" @click="selectAvatar">
            <van-icon name="user-o" size="40" />
          </view>
        </view>
        <view class="user-details">
          <view v-if="isLogin" class="user-name">{{ userInfo.username }}</view>
          <view v-else class="login-prompt" @click="goLoginPage">点击登录</view>
          <view v-if="isLogin" class="user-phone">{{ userInfo.phone }}</view>
        </view>
      </view>
      <view v-if="isLogin" class="user-stats">
        <view class="stat-item">
          <view class="stat-number">{{ userStats.appointments }}</view>
          <view class="stat-label">预约</view>
        </view>
        <view class="stat-item">
          <view class="stat-number">{{ userStats.consultations }}</view>
          <view class="stat-label">问诊</view>
        </view>
        <view class="stat-item">
          <view class="stat-number">{{ userStats.reports }}</view>
          <view class="stat-label">报告</view>
        </view>
      </view>
    </view>

    <!-- 快捷功能 -->
    <view class="quick-actions">
      <van-grid :column-num="4" :border="false" :gutter="16">
        <van-grid-item
          v-for="action in quickActions"
          :key="action.name"
          @click="navigateToAction(action)"
        >
          <van-icon :name="action.icon" size="24" :color="action.color" />
          <text class="action-text">{{ action.name }}</text>
        </van-grid-item>
      </van-grid>
    </view>

    <!-- 医疗记录 -->
    <view class="medical-records">
      <van-cell-group>
        <van-cell title="医疗记录" :border="false" />
        <van-cell
          v-for="record in medicalRecords"
          :key="record.id"
          :title="record.title"
          :label="record.description"
          is-link
          @click="navigateToRecord(record)"
        >
          <template #icon>
            <van-icon :name="record.icon" :color="record.color" />
          </template>
          <template #right-icon>
            <view v-if="record.count > 0" class="record-count">{{
              record.count
            }}</view>
          </template>
        </van-cell>
      </van-cell-group>
    </view>

    <!-- 设置选项 -->
    <view class="settings">
      <van-cell-group>
        <van-cell title="设置" :border="false" />
        <van-cell
          v-for="setting in settingOptions"
          :key="setting.id"
          :title="setting.title"
          :value="setting.value"
          is-link
          @click="handleSetting(setting)"
        >
          <template #icon>
            <van-icon :name="setting.icon" :color="setting.color" />
          </template>
        </van-cell>
      </van-cell-group>
    </view>

    <!-- 其他功能 -->
    <view class="other-functions">
      <van-cell-group>
        <van-cell title="意见反馈" is-link @click="handleFeedback">
          <template #icon>
            <van-icon name="chat-o" color="#ff6b35" />
          </template>
        </van-cell>
        <van-cell title="关于我们" is-link @click="handleAbout">
          <template #icon>
            <van-icon name="info-o" color="#1989fa" />
          </template>
        </van-cell>
        <van-cell v-if="isLogin" title="退出登录" @click="handleLogout">
          <template #icon>
            <van-icon name="revoke" color="#ee0a24" />
          </template>
        </van-cell>
      </van-cell-group>
    </view>

    <!-- 底部导航 -->
    <TabBar currentTab="profile" />
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores";
import { logout, getInfo } from "@/api/user";
import { ref } from "vue";

const userStore = useUserStore();
const userInfo = userStore.userInfo;
const isLogin = userStore.isLogin;
console.log("个人中心页面 userStore:", userStore.token);
console.log("个人中心页面 isLogin:", userStore);

const userStats = {
  appointments: 3,
  consultations: 2,
  reports: 5,
};
const quickActions = [
  {
    name: "预约挂号",
    icon: "calendar-o",
    color: "#07C160",
    url: "/pages/appointment/department-select",
  },
  {
    name: "问诊记录",
    icon: "chat-o",
    color: "#ff6b35",
    url: "/pages/profile/consultation-history",
  },
  {
    name: "体检报告",
    icon: "records",
    color: "#1989fa",
    url: "/pages/profile/exam-reports",
  },
  {
    name: "健康档案",
    icon: "manager-o",
    color: "#9c5cff",
    url: "/pages/profile/health-profile",
  },
];

const medicalRecords = [
  {
    id: "appointments",
    title: "挂号记录",
    description: "查看历史挂号记录",
    icon: "calendar-o",
    color: "#07C160",
    count: 3,
    url: "/pages/profile/appointment-history",
  },
  {
    id: "medical",
    title: "诊疗记录",
    description: "查看诊疗详情和病历",
    icon: "records",
    color: "#1989fa",
    count: 5,
    url: "/pages/profile/medical-records",
  },
  {
    id: "prescriptions",
    title: "历史处方",
    description: "查看开具的处方信息",
    icon: "description",
    color: "#ff6b35",
    count: 2,
    url: "/pages/profile/prescription-history",
  },
  {
    id: "reports",
    title: "检查报告",
    description: "查看各类检查报告",
    icon: "newspaper-o",
    color: "#9c5cff",
    count: 4,
    url: "/pages/profile/exam-reports",
  },
];

const settingOptions = [
  {
    id: "notification",
    title: "消息设置",
    value: "开启",
    icon: "bell-o",
    color: "#ff6b35",
  },
  {
    id: "privacy",
    title: "隐私设置",
    value: "",
    icon: "lock",
    color: "#1989fa",
  },
  {
    id: "language",
    title: "语言设置",
    value: "简体中文",
    icon: "language-o",
    color: "#07C160",
  },
];

const navigateToAction = (action: any) => {
  if (!isLogin.value) {
    goLoginPage();
    return;
  }
  uni.navigateTo({
    url: action.url,
  });
};

const navigateToRecord = (record: any) => {
  // if (!isLogin.value) {
  //   goLoginPage();
  //   return;
  // }
  // uni.navigateTo({
  //   url: record.url,
  // });

  if (!userStore.token) {
    goLoginPage();
    return;
  }
  uni.navigateTo({ url: record.url });

};

const selectAvatar = () => {
  if (!isLogin.value) {
    goLoginPage();
    return;
  }

  uni.chooseImage({
    count: 1,
    success: (res) => {
      userStore.updateAvatar(res.tempFilePaths[0]);
      uni.showToast({
        title: "头像更新成功",
        icon: "success",
      });
    },
  });
};

const handleSetting = (setting: any) => {
  console.log("设置:", setting);
  uni.showToast({
    title: "功能开发中",
    icon: "none",
  });
};

const handleFeedback = () => {
  uni.showToast({
    title: "功能开发中",
    icon: "none",
  });
};

const handleAbout = () => {
  uni.showModal({
    title: "关于云医通",
    content: "云医通 v1.0.0\n智能医疗服务小程序\n为您提供便捷的医疗服务",
    showCancel: false,
  });
};

const handleLogout = async () => {
  const res = await uni.showModal({
    title: "退出登录",
    content: "确定要退出登录吗？",
    showCancel: true,
  });
  if (res.confirm) {
    try {
      await logout();
    } catch (e) {}
    userStore.logout();
    uni.showToast({
      title: "已退出登录",
      icon: "success",
    });
  }
};

const goLoginPage = () => {
  uni.navigateTo({
    url: "/pages/login/index",
  });
};

onLoad(() => {
  console.log("个人中心页面 onLoad");
});

onShow(async () => {
  console.log("个人中心页面 onShow,userStore.token", userStore.token);

  // 如果用户已登录，调用getInfo接口获取用户信息
  if (userStore.token) {
    try {
      const res = await getInfo();
      console.log("获取用户信息:", res);

      if (res.code === 200) {
        // 将返回的完整数据保存到Pinia中（响应式更新 userInfo）
        userStore.setUserData(res.data);
        console.log("用户信息已更新到Pinia:", userStore.userData);
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
    }
  }
});
</script>

<style lang="scss">
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 100rpx;
}

.user-header {
  background: linear-gradient(135deg, #07c160 0%, #05a050 100%);
  color: white;
  padding: 48rpx 32rpx 32rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 48rpx;
}

.avatar-section {
  margin-right: 32rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.avatar-placeholder {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.login-prompt {
  font-size: 36rpx;
  color: rgba(255, 255, 255, 0.9);
}

.user-phone {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.user-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.quick-actions {
  background: white;
  margin: 16rpx 24rpx;
  border-radius: 16rpx;
  padding: 32rpx 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.action-text {
  font-size: 24rpx;
  color: #323233;
  margin-top: 8rpx;
  display: block;
}

.medical-records,
.settings,
.other-functions {
  background: white;
  margin: 16rpx 24rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.record-count {
  background: #ee0a24;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  min-width: 32rpx;
  text-align: center;
  margin-left: 16rpx;
}
</style>
